package com.bsoft.advance.client.transport;

import io.netty.channel.Channel;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 复用channel的缓存map
 */
public class ChannelProvider {
    /**
     * {"host:port",channel}
     */
    private static Map<String, Channel> channelMap = new ConcurrentHashMap<>();

    /**
     * 存入map
     *
     * @param socketAddress
     * @param channel
     */
    public static void put(InetSocketAddress socketAddress, Channel channel) {
        channelMap.put(socketAddress.toString(), channel);
    }

    /**
     * 获取channel
     *
     * @param socketAddress
     * @return
     */
    public static Channel get(InetSocketAddress socketAddress) {
        String key = socketAddress.toString();
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        if(channelMap.containsKey(key)){
            Channel channel = channelMap.get(key);
            if (channel != null && channel.isActive()) {
                return channel;
            }else{
                // 清理无效通道
                channelMap.remove(key);
            }
        }
        return null;
    }

}
